import re

from django.core.validators import FileExtensionValidator
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
from FmyTest.models import versioncontrol

STATUS_CHOICES = (('0', '排队中'), ('1', '打包中'), ('2', '上传中'), ('3', '已完成'), ('4', '暂停'))


class cputype(models.TextChoices):
    arm64 = 'arm64', 'arm64'
    amd64 = 'amd64', 'amd64'

def versiontype():
    # 获取字段的值
    results = versioncontrol.objects.filter(stats='s').values_list('soft_version', flat=True)
    data = []
    if results:
        for i in list(results):
            data.append((i, i))
    else:
        data.append(('0', '目前没有可用版本'))
    return tuple(data)

def validate_license(value):
    ext = value.name.split('.')[-1]
    allowed_extensions = ['lic']
    # print(data.license.read(),'licensevalue')
    if ext not in allowed_extensions:
        raise ValidationError("文件格式不是lic")
    print(data.license.read().decode('utf-8'),'license')
    if data.objects.filter(license__contains=data.license):
        raise ValidationError('数据库中已经存在相同的license\n请若要保存新的license，请先删除原来的license！！')


def versioncheck(value):
    if value == '0':
        raise ValidationError('请您联系管理员添加相应版本!!')


# Create your models here.
class data(models.Model):
    name = models.CharField(max_length=32, verbose_name='客户名称', editable=False)
    soft_version = models.ForeignKey(to='FmyTest.versioncontrol', on_delete=models.CASCADE)
    cpu = models.CharField(max_length=32, choices=cputype.choices, default=cputype.amd64, verbose_name='CPU类型')
    license = models.FileField(verbose_name='license文件', upload_to='upload/', validators=[FileExtensionValidator(allowed_extensions=['lic'])], )
    # license = models.FileField(verbose_name='license文件', upload_to='upload/',validators=[validate_license])
    email = models.EmailField()
    lic_md5 = models.CharField(max_length=32, default='', editable=False)
    pack_name = models.CharField(max_length=255, default='', editable=False)
    pack_md5 = models.CharField(max_length=32, default='', editable=False)
    stats = models.CharField(max_length=1, choices=STATUS_CHOICES, verbose_name="状态", default="0", editable=False)
    create_time = models.DateTimeField(default=timezone.now, editable=False)
    update_time = models.DateTimeField(default=timezone.now, editable=False)
    starttime = models.DateTimeField(default=None, null=True, editable=False)
    endtime = models.DateTimeField(default=None, null=True, editable=False)

    class Meta:
        verbose_name = 'license上传记录'
        verbose_name_plural = 'license上传记录'

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.license:
            # 对上传的lic进行重命名
            print('############')
            original_name = self.license.name.split('/')[-1]
            content = self.license.read().decode('utf-8').splitlines()
            cust_name = [line for line in content if line.startswith('Licensee=')][0].split('=')[1]
            new_name = "{}_{}_{}_{}_license.lic".format(cust_name,self.soft_version,self.cpu,self.email.replace('@','_'))
            self.name = cust_name
            # 这样替换名字的话，就不会把路径丢失！！
            self.license.name = self.license.name.replace(original_name,new_name)
            # if data.objects.filter(license__contains=cust_name + '_' + self.soft_version + '_' + self.cpu):
            #     print('hhh2')
            #     raise ValidationError ('数据库中已经存在相同的license,请若要保存新的license，请先删除原来的license！！')
            self.license_name = new_name
            # self.version = self.soft_version
            super(data, self).save(*args, **kwargs)

    # 每次重新查询表中的有效取值，而后重新给data.soft_version字段的choices字段赋值
    # def __init__(self, *args, **kargs):
    #     super(data, self).__init__(*args, **kargs)
    #     self._meta.get_field('soft_version').choices = versiontype()

# @receiver(pre_save, sender=data)
# def rename_file(sender, instance, **kwargs):
#     filename = instance.license.name
#     print('******')
#     print(filename)
#     instance.license.name = '#'+filename
#     # instance.file.name = slugify(filename)